<template>
  <div class="user-management-container">
    <el-card class="user-management-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">用户管理</span>
          <div class="header-actions">
            <el-button
                type="primary"
                @click="fetchUsers"
                :icon="Refresh"
                :loading="loading"
            >
              刷新
            </el-button>
            <el-button
                type="success"
                @click="openCreateDialog"
                :icon="Plus"
            >
              新建用户
            </el-button>
          </div>
        </div>
      </template>

      <div class="table-container">
        <el-table
            :data="paginatedUsers"
            border
            style="width: 100%"
            v-loading="loading"
            stripe
            highlight-current-row
            :header-cell-style="{background: '#f5f7fa', color: '#606266'}"
            :row-class-name="tableRowClassName"
        >
          <el-table-column label="序号" width="80" align="center">
            <template #default="{ $index }">
              {{ (currentPage - 1) * pageSize + $index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="username" label="用户名" width="120" align="center" />
          <el-table-column prop="phone" label="手机号" width="150" align="center">
            <template #default="{row}">
              <el-tooltip effect="dark" :content="row.phone" placement="top">
                <span>{{ row.phone }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="role" label="角色" width="120" align="center">
            <template #default="{row}">
              <el-tag :type="getRoleTagType(row.role)" effect="dark">
                {{ formatRole(row.role) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="permission" label="权限" width="120" align="center">
            <template #default="{row}">
              <el-tag :type="getPermissionTagType(row.permission)" effect="dark">
                {{ formatPermission(row.permission) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="120" align="center">
            <template #default="{row}">
              <div class="status-container">
                <el-tag
                    :type="row.status === 1 ? 'success' : 'danger'"
                    :effect="row.status === 1 ? 'light' : 'dark'"
                    size="small"
                    class="status-tag"
                >
                  <span class="status-text">
                    {{ row.status === 1 ? '正常' : '禁用' }}
                  </span>
                </el-tag>
                <el-switch
                    v-model="row.status"
                    :active-value="1"
                    :inactive-value="0"
                    @change="handleStatusChange(row)"
                    active-text=""
                    inactive-text=""
                    active-color="#67C23A"
                    inactive-color="#F56C6C"
                    class="status-switch"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" align="center">
            <template #default="{row}">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="lastLoginTime" label="最后登录" width="180" align="center">
            <template #default="{row}">
              {{ row.lastLoginTime ? formatDate(row.lastLoginTime) : '从未登录' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" align="center" fixed="right">
            <template #default="scope">
              <el-button
                  type="primary"
                  size="small"
                  @click="openEditDialog(scope.row)"
                  :icon="Edit"
                  circle
                  title="编辑用户"
              />
              <el-button
                  type="danger"
                  size="small"
                  @click="handleDelete(scope.row.id)"
                  :icon="Delete"
                  circle
                  title="删除用户"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="userList.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑用户弹窗 -->
    <el-dialog
        v-model="editDialogVisible"
        :title="editFormData.id ? '编辑用户信息' : '新建用户'"
        width="600px"
        :close-on-click-modal="false"
    >
      <el-form
          ref="editForm"
          :model="editFormData"
          label-width="100px"
          label-position="right"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editFormData.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!editFormData.id">
          <el-input v-model="editFormData.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editFormData.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="editFormData.role" placeholder="请选择角色" style="width: 100%">
            <el-option
                v-for="(role, key) in roleOptions"
                :key="key"
                :label="role"
                :value="Number(key)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="权限" prop="permission">
          <el-select v-model="editFormData.permission" placeholder="请选择权限" style="width: 100%">
            <el-option
                v-for="(permission, key) in permissionOptions"
                :key="key"
                :label="permission"
                :value="Number(key)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
              v-model="editFormData.status"
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
              active-color="#67C23A"
              inactive-color="#F56C6C"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Edit, Delete, Plus } from '@element-plus/icons-vue'

const userList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const small = ref(false)
const disabled = ref(false)
const background = ref(true)

// 编辑弹窗相关状态
const editDialogVisible = ref(false)
const editFormData = ref({
  id: null,
  username: '',
  password: '',
  phone: '',
  role: null,
  permission: null,
  status: 1
})
const roleOptions = ref({
  1: '普通用户',
  2: '商家',
  3: '管理员'
})
const permissionOptions = ref({
  0: '无',
  1: '管理员'
})

const paginatedUsers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return userList.value.slice(start, end)
})

const handleSizeChange = (val) => {
  pageSize.value = val
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

const fetchUsers = async () => {
  try {
    loading.value = true
    const response = await axios.get(BASE_URL + '/api/v1/admin/selAllUser')
    userList.value = response.data.data.map(user => ({
      ...user,
      createTime: typeof user.createTime === 'string' ? user.createTime : new Date(user.createTime).toISOString(),
      lastLoginTime: user.lastLoginTime ? (typeof user.lastLoginTime === 'string' ? user.lastLoginTime : new Date(user.lastLoginTime).toISOString()) : null
    }))
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

const formatRole = (role) => {
  return roleOptions.value[role] || '未知'
}

const getRoleTagType = (role) => {
  const types = {
    1: 'info',
    2: 'warning',
    3: 'danger'
  }
  return types[role] || 'info'
}

const formatPermission = (permission) => {
  return permissionOptions.value[permission] || '未知'
}

const getPermissionTagType = (permission) => {
  const types = {
    0: '',
    1: 'success',
    2: 'warning'
  }
  return types[permission] || ''
}

const formatDate = (dateString) => {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  }).replace(/\//g, '-')
}

const openEditDialog = (user) => {
  editFormData.value = {
    id: user.id,
    username: user.username,
    phone: user.phone,
    role: user.role,
    permission: user.permission,
    status: user.status,
    password: ''
  }
  editDialogVisible.value = true
}

const openCreateDialog = () => {
  editFormData.value = {
    id: null,
    username: '',
    password: '',
    phone: '',
    role: null,
    permission: null,
    status: 1
  }
  editDialogVisible.value = true
}

const submitEditForm = async () => {
  try {
    // 基本验证
    if (!editFormData.value.username) {
      ElMessage.warning('请输入用户名')
      return
    }

    if (!editFormData.value.id && !editFormData.value.password) {
      ElMessage.warning('新建用户请输入密码')
      return
    }


    let response = await axios.post(BASE_URL+'/api/v1/admin/revise', editFormData.value)
    if (response.data.code == 2000){
      ElMessage.success('操作成功');
      editDialogVisible.value = false;
      fetchUsers();
    }


  } catch (error) {
    console.error('操作失败:', error)
    const errorMsg = error.response?.data?.message || error.message || '请求失败，请检查网络'
    ElMessage.error(errorMsg)
  }
}

const handleDelete = (id) => {
  if (confirm('确定要删除该用户吗')){
    axios.post(BASE_URL+'/api/v1/admin/delUser', null,{params:  {userId: id}})
        .then((response)=>{
          if (response.data.code == 2000){
            ElMessage.success('删除成功');
            fetchUsers();
          }else{
            ElMessage.error(response.data.message);
          }
        })
  }
}

const handleStatusChange = async (user) => {
  try {
    const params = {
      id: user.id,
      status: Number(user.status)
    }
    await axios.post(BASE_URL + '/api/v1/admin/revise', params)
    ElMessage.success('状态更新成功')
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('更新状态失败')
    user.status = user.status === 1 ? 0 : 1
  }
}

const tableRowClassName = ({rowIndex}) => {
  return rowIndex % 2 === 0 ? 'even-row' : 'odd-row'
}

onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.user-management-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 60px);
}

.user-management-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.table-container {
  margin-top: 10px;
  padding: 0 10px;
}

.el-table {
  font-size: 14px;
}

.el-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.el-button {
  margin: 0 5px;
}

/* 状态列样式 */
.status-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.status-tag {
  min-width: 60px;
  text-align: center;
  border-radius: 12px;
  font-weight: 500;
}

.status-text {
  font-size: 12px;
}

.status-switch {
  margin-left: 8px;
}

/* 自定义行样式 */
:deep(.el-table .even-row) {
  background-color: #fafafa;
}

:deep(.el-table .odd-row) {
  background-color: #ffffff;
}

/* 标签样式增强 */
:deep(.el-tag) {
  font-weight: 500;
  letter-spacing: 0.5px;
}

/* 操作按钮悬停效果 */
.el-button:hover {
  transform: scale(1.05);
  transition: transform 0.2s;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 弹窗样式 */
:deep(.el-dialog__body) {
  padding: 20px 30px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style>